
window.cart = [];


window.loadCart = function() {
    console.log('Loading cart from localStorage...');
    try {
        const savedCart = localStorage.getItem('cart');
        console.log('Raw cart data from localStorage:', savedCart);
        
        if (savedCart) {
            window.cart = JSON.parse(savedCart);
            console.log('Successfully loaded cart:', window.cart);
        } else {
            console.log('No cart data found in localStorage');
            window.cart = [];
        }
    } catch (error) {
        console.error('Error loading cart:', error);
        window.cart = [];
    }
}


window.saveCart = function() {
    console.log('Saving cart to localStorage...');
    try {
        const cartString = JSON.stringify(window.cart);
        console.log('Cart data to save:', cartString);
        localStorage.setItem('cart', cartString);
        console.log('Cart saved successfully');
    } catch (error) {
        console.error('Error saving cart:', error);
    }
}


window.increaseQuantity = function(productName) {
    console.log('Increasing quantity for:', productName);
    const quantityInput = document.getElementById(`${productName}-quantity`);
    if (quantityInput) {
        const currentValue = parseInt(quantityInput.value);
        quantityInput.value = currentValue + 1;
        console.log('New quantity:', quantityInput.value);
    } else {
        console.error('Quantity input not found for:', productName);
    }
}


window.decreaseQuantity = function(productName) {
    console.log('Decreasing quantity for:', productName);
    const quantityInput = document.getElementById(`${productName}-quantity`);
    if (quantityInput && parseInt(quantityInput.value) > 1) {
        const currentValue = parseInt(quantityInput.value);
        quantityInput.value = currentValue - 1;
        console.log('New quantity:', quantityInput.value);
    } else {
        console.log('Cannot decrease quantity below 1');
    }
}


window.addToCart = function(productName, price) {
    console.log('Adding to cart:', { productName, price });
    
    const quantityInput = document.getElementById(`${productName}-quantity`);
    if (!quantityInput) {
        console.error('Quantity input not found for:', productName);
        alert('Error: Could not find quantity input for ' + productName);
        return;
    }

    const quantity = parseInt(quantityInput.value);
    console.log('Selected quantity:', quantity);
    
    if (isNaN(quantity) || quantity < 1) {
        console.error('Invalid quantity:', quantity);
        alert('Please select a valid quantity');
        return;
    }

    
    const existingItem = window.cart.find(item => item.name === productName);
    if (existingItem) {
        console.log('Item already in cart, updating quantity');
        existingItem.quantity += quantity;
    } else {
        console.log('Adding new item to cart');
        window.cart.push({
            name: productName,
            price: price,
            quantity: quantity
        });
    }

    window.saveCart();
    console.log('Current cart state:', window.cart);
    alert('Added to cart: ' + productName + ' x' + quantity);
    quantityInput.value = 1; 
}


window.updateCartDisplay = function() {
    console.log('Updating cart display...');
    const cartItems = document.getElementById('cart-items');
    const totalElement = document.getElementById('total-price');
    
    if (!cartItems || !totalElement) {
        console.error('Could not find cart elements:', { cartItems, totalElement });
        return;
    }

  
    cartItems.innerHTML = '';
    console.log('Current cart:', window.cart);
    
    if (!window.cart || window.cart.length === 0) {
        console.log('Cart is empty');
        cartItems.innerHTML = '<p>Your cart is empty</p>';
        totalElement.textContent = '€0.00';
        return;
    }

    let total = 0;
    window.cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        console.log('Processing item:', item, 'Total:', itemTotal);

        const itemElement = document.createElement('div');
        itemElement.className = 'cart-item';
        itemElement.innerHTML = `
            <span>${item.name}</span>
            <span>€${item.price.toFixed(2)}</span>
            <span>${item.quantity}</span>
            <span>€${itemTotal.toFixed(2)}</span>
            <button onclick="window.removeFromCart('${item.name}')">Remove</button>
        `;
        cartItems.appendChild(itemElement);
    });

    console.log('Final total:', total);
    totalElement.textContent = `€${total.toFixed(2)}`;
}


window.removeFromCart = function(productName) {
    console.log('Removing from cart:', productName);
    window.cart = window.cart.filter(item => item.name !== productName);
    console.log('Cart after removal:', window.cart);
    window.saveCart();
    window.updateCartDisplay();
}


window.checkout = function() {
    console.log('Processing checkout...');
    if (!window.cart || window.cart.length === 0) {
        console.log('Cart is empty, cannot checkout');
        alert('Your cart is empty');
        return;
    }
    
    alert('Thank you for your purchase!');
    window.cart = [];
    window.saveCart();
    window.updateCartDisplay();
}


document.addEventListener('DOMContentLoaded', function() {
    window.loadCart();
    window.updateCartDisplay();
});
